package spring.springbucks.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import spring.springbucks.enums.OrderStateEnum;
import spring.springbucks.service.CoffeeOrderManagementService;
import spring.springentity.entity.table.CoffeeEntity;
import spring.springentity.entity.table.OrderEntity;
import spring.springentity.repository.CoffeeRepository;
import spring.springentity.repository.OrderCoffeeRepository;
import spring.springentity.repository.OrderRepository;

@Slf4j
@Service
public class CoffeeOrderManagementServiceImpl implements CoffeeOrderManagementService {

  @Autowired
  private OrderCoffeeRepository orderCoffeeRepository;

  @Autowired
  private OrderRepository orderRepository;

  @Autowired
  private CoffeeRepository coffeeRepository;

  @Transactional(rollbackFor = Exception.class)
  public OrderEntity createOrder(String customer, String... coffees) {

    OrderEntity customOrder = new OrderEntity();
    customOrder.setCustomer(customer);
    customOrder.setState(OrderStateEnum.INIT.getValue());
    orderRepository.save(customOrder);
    log.info("New Order: {}", customOrder);

    coffeeRepository.list(new QueryWrapper<CoffeeEntity>().in("NAME", coffees).eq("SYS_IS_DELETED", 0));

    return customOrder;
  }

  public boolean updateState(OrderEntity order, OrderStateEnum state) {
    //if (state.compareTo(order.getState()) <= 0) {
    //  log.warn("Wrong State order: {}, {}", state, order.getState());
    //  return false;
    //}
    //order.setState(state);
    //orderRepository.save(order);
    //log.info("Updated Order: {}", order);
    return true;
  }
}
